﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading;
namespace 消费Rabbit消息
{
    class Program
    {
        static void Main(string[] args)
        {
            string queueName = "queue1";
            Console.WriteLine($"监听消息:{queueName}");
            ConnectionFactory factory = new ConnectionFactory() { HostName="localhost"};
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    // 声明队列
                    channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false);

                    // 定义消费者
                    var consumer = new EventingBasicConsumer(channel);

                    // 接收事件 public delegate void EventHandler<TEventArgs>(object? sender, TEventArgs e);
                    consumer.Received += (model, ea) =>
                    {
                        // 接收到的消息
                        byte[] message = ea.Body.ToArray();

                        Console.WriteLine(Encoding.UTF8.GetString(message));
                        // 返回消息确认
                        channel.BasicAck(ea.DeliveryTag, true);
                    };
                    // 开启监听
                    channel.BasicConsume(queueName, false, consumer);
                }
            };

            Thread.Sleep(1000*60);


            Console.ReadKey();
        }
    }
}
